<template>

  <view class="grid">
    <view class="content">
      <view>
        <text style="font-size: 1.2em;">错误总揽</text>
        <text style="margin-left: 10rpx;color: #cacdd1;">overview</text>
      </view>

      <view v-if="!isMobile" class="search">
        <view @click="open()">
          <uni-icons style="padding: 0px 5px 0px 5px;" type="tune" size="20"></uni-icons>筛选
        </view>
        <uni-datetime-picker style="flex:2;" :border="true" type="datetimerange" :end="new Date().getTime()"
          v-model="seachtime" :clearIcon="false" class="uni-stat-datetime-picker"
          :class="{ 'uni-stat__actived': currentDateTab < 0 && !!seachtime }" @change="SearchData" />

        <uni-easyinput style="flex:3;" prefixIcon="search" trim="all" v-model="value" placeholder="请输入内容"
          @input="input"></uni-easyinput>
        <view>
          <uni-icons style="padding: 0px 5px 0px 5px;" type="download" size="20"
            @click="ExportWorlBook()">导出</uni-icons>
        </view>
        <DeviceVue style="flex:2;" :deviceList="deviceList" @changedevice="Changedevice"></DeviceVue>
      </view>
      <view v-if="isMobile">
        <view class="search">
          <view @click="open()">
            <uni-icons style="padding: 0px 5px 0px 5px;" type="tune" size="20"></uni-icons>筛选
          </view>
          <uni-datetime-picker :border="true" type="datetimerange" :end="new Date().getTime()" v-model="seachtime"
            :clearIcon="false" class="uni-stat-datetime-picker"
            :class="{ 'uni-stat__actived': currentDateTab < 0 && !!seachtime }" @change="SearchData" />
        </view>
        <view class="search">
          <view>
            <uni-icons style="padding: 0px 5px 0px 5px;" type="download" size="20"
              @click="ExportWorlBook()">导出</uni-icons>
          </view>
          <DeviceVue style="flex:2;" :deviceList="deviceList" @changedevice="Changedevice"></DeviceVue>
          <uni-easyinput style="flex:3;" prefixIcon="search" trim="all" v-model="value" placeholder="请输入内容"
            @input="input"></uni-easyinput>
        </view>
      </view>
      <uni-table class="table" ref="table" :loading="loading" type="" emptyText="暂无更多数据">
        <uni-tr>
          <uni-th :width="isMobile ?  50:100" align="center">机房编号</uni-th>
          <uni-th :width="isMobile ? 50 : 200" align="center">警告</uni-th>
          <uni-th :width="isMobile ? 20 : 200" align="center">详细</uni-th>
          <uni-th :width="isMobile ? 70 : 200" align="center">时间</uni-th>
        </uni-tr>
        <uni-tr v-for="(item, index) in Error_Data" :key="index">
          <uni-td align="center">{{ item.e_no }}</uni-td>
          <uni-td align="center">{{ item.type }}</uni-td>
          <uni-td align="center">{{ item.e_msg }}</uni-td>
          <uni-td align="center">
            <view style="width: 1px;height: 15px;"></view>
            {{ item.c_time }}
          </uni-td>
        </uni-tr>
      </uni-table>

      <uni-pagination style="border-radius: 0px 0px 10px 10px;" :show-icon="true" :current="current" :total="total"
        @change="PageChange" />

    </view>
  </view>
  <uni-popup ref="popup" mask-background-color="rgba(0,0,0,0.2)" background-color="#fff" type="right" border-radius="0">
    <view class="flex" style="width: 50vw;height: 50px ;border-bottom: 1.5px solid  rgb(230,231,235);">
      <uni-icons color="rgb(109,114,127)" style="border-radius: 10px;border:2px solid;border-color:rgb(230,231,235);"
        type="closeempty" size="20" @click="RefreshData"></uni-icons>
      <text style="margin-top: 140rpx;font-weight: 600;font-size: 0.9em;">查询错误记录</text>
      <view style="width: 100%;height: 1px;"></view>
      数据异常<switch @click="Invade"></switch>人员入侵
    </view>
  </uni-popup>


</template>
<script>
import ChartsVue from '@/components/functions/Charts.vue';
import DeviceVue from '@/components/functions/Device.vue';
import ExcelJS from 'exceljs';
import { useDeviceDetection } from '@/hooks/useDeviceDetection';
export default {
  components: {
    ChartsVue,
    DeviceVue,
  },
  data() {
    return {
      loading: false,
      current: 0,
      total: 0,
      id: 0,
      timecurrent: 3,
      times: ['今天', '一周', '所有'],
      deviceList: [],
      Scene: [],
      Error_Data: [],
      seachtime: ['', ''],
      currentDateTab: 2,
      ws: null,
      items: ['选项卡1', '选项卡2', '选项卡3'],
      invade: false
    }
  },
  setup() {
    const { isMobile } = useDeviceDetection();
    return { isMobile };
  },
  methods: {
    open() {
      // 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
      this.$refs.popup.open()
    },
    Changetimetabs(e) {
      this.timecurrent = e.currentIndex;
      //今天
      if (e.currentIndex == 0) {
        this.seachtime = [new Date().toLocaleDateString(), new Date().toLocaleDateString()];
      }
      //最近一周
      else if (e.currentIndex == 1) {
        let date = new Date();
        let se = new Date(date.getTime() - 7 * 24 * 60 * 60 * 1000);
        this.seachtime = [se.toLocaleDateString(), date.toLocaleDateString()];
      }
      //最近30天
      else if (e.currentIndex == 2) {
        let date = new Date();
        let se = new Date(date.getTime() - 30 * 24 * 60 * 60 * 1000);
        this.seachtime = [se.toLocaleDateString(), date.toLocaleDateString()];
      }

      //所有
      else if (e.currentIndex == 3) {
        this.seachtime = ['', ''];
      }
      this.SearchData();
    },
    PageChange(e) {
      this.current = e.current;
      this.SendDate((this.current - 1) * 10);
    },
    SearchData() {
      this.current = 0;
      this.SendDate((this.current) * 10);
    },
    SendDate(page) {
      let st = this.seachtime[0];
      let ed = this.seachtime[1];
      if (st === '' || st == undefined) {
        st = "1970-01-01";
      }
      if (ed === '' || ed == undefined) {
        ed = "2032-01-01";
      }
      let datatype = "Page";
      if (this.invade) {
        datatype = "invade";
      }
      this.ws.send({
        data: JSON.stringify({
          pageIndex: page,
          type: datatype,
          startDate: st + ' 00:00',
          endDate: ed + ' 23:59',
          d_no:this.id
        })
      });
      this.Error_Data = [];
    },
    Changedevice(e) {
      this.pagecurrent = 0;
      this.id = e
      this.SendDate(this.pagecurrent);
    },
    Invade() {
      this.invade = !this.invade;
      this.pagecurrent = 0;
      this.SendDate(this.pagecurrent);
    },
    ExportWorlBook() {
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('Sheet 1'); // 创建一个工作表

      // 设置列标题
      worksheet.columns = [{
        header: '机房编号',
        key: 'e_no',
        width: 20
      },
      {
        header: '警告',
        key: 'type',
        width: 10
      },
      {
        header: '时间',
        key: 'c_time',
        width: 30
      }
      ];

      worksheet.addRows(this.Error_Data); // 添加数据行

      // 创建一个 Blob 并下载文件
      workbook.xlsx.writeBuffer().then((buffer) => {
        const blob = new Blob([buffer], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'example.xlsx';
        link.click(); // 模拟点击下载文件
      });

    }

  },
  created() {
    uni.hideTabBar({});
    this.ws = uni.connectSocket({
      url: 'ws://192.168.1.111:8080/ErrorData',
      //url: 'ws://192.168.1.101:8000/ErrorData',
      //url: 'ws://192.168.116.89:8000/ErrorData',
      success: () => {
        console.log('WebSocket连接成功');
      }
    });
    this.ws.onOpen(() => {
      console.log('WebSocket连接已打开！');
    });
    this.ws.onMessage((e) => {
      let obj = JSON.parse(e.data);
      console.log(obj)
      switch (obj.topic) {
        case 'device':
          obj.data.forEach((item) => {
            this.deviceList.push({
              value: item.id,
              text: item.device_name,
            });
          })
          break;
        case 'sence':
          this.Scene = obj.data
          break;
        case 't_error_msg_count':
          this.total = obj.data[0].count;
          break;
        case 't_error_msg':
          this.Error_Data = obj.data;
          break;
        default:
          break;
      }

    })
    this.ws.onClose(() => {
      console.log('WebSocket已关闭');
    });
  },
  beforeDestroy() {
    console.log('组件销毁');
    this.ws.close();
  }
}
</script>

<style lang="scss" scoped>
$uni-success: #18bc37 !default;

.grid {
    display: flex;
      justify-content: center;
      padding: 20rpx;
      font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, SimSun, sans-serif;
}
.content{
 width: 100%;
}
.search {
  /* width: 100%; */
  margin-top: 30rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}
.table{
    margin-top: 30rpx;
    border-radius: 0px 10px 0px 0px;
    border-top: 2px solid;
    border-bottom: 2px solid;
    border-color: #ebeef5;
}
.DeviceForm {
  padding: 15px;
  background-color: #fff;
}

.uni-stat--x {
  border-radius: 4px;
  box-shadow: -1px -1px 5px rgba(0, 0, 0, .1);
  margin-bottom: 15px;
}

.flex {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  padding: 10rpx;
}

.p-1015 {
  padding: 10px 15px;
}

.border-20 {
  border: 2px solid;
  border-color: rgb(230, 231, 235);
}

.uni-stat--app-select {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  width: 900px;
  max-width: 100%;
}
</style>